<?php

namespace Product\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Product\Form\CreateProduct;

use Product\Entity\Product;
use Product\Entity\Brand;
use Product\Entity\Category;

class IndexController extends AbstractActionController {

    public function indexAction() {
        $form = new CreateProduct();
        
        $product = new Product();
        $form->bind($product);
        
        $request = $this->getRequest();
        
        if($request->isPost())
        {            
            $form->setData($request->getPost());
            if($form->isValid())
            {
                $data = $request->getPost();
                
                $brand = new Brand();
                $brand->populate($data['product']['brand']);
                $brand_id = $this->getBrandTable()->saveBrand($brand);
                
		$category = new Category();
		$data['product']['category'] = array('name' => 'huy');
		$category->populate($data['product']['category']);
		$category_id = $this->getCategoryTable()->saveCategory($category);		
		
		//$data['product']['brand_id'] = $brand_id;
		//$data['product']['category_id'] = $category_id;
		
		//$product->setBrand($brand_id);
		//$product->setCategories($category_id);
				
                $product->populate($data['product']); die(print_r($data['product']));
                $this->getProductTable()->saveProduct($product);
                var_dump($request->getPost());
            }        
            var_dump($request->getPost());
        }
        return array(
            'form' => $form,
        );
    }
    
    protected $productTable;
    
    public function getProductTable()
    {
        if(!$this->productTable)
        {
            $sm = $this->getServiceLocator();
            $this->productTable = $sm->get('Product\Model\Product');
        }
        return $this->productTable;
    }
    
    protected $brandTable;
    public function getBrandTable()
    {
        if(!$this->brandTable)
        {
            $sm = $this->getServiceLocator();
            $this->brandTable = $sm->get('Product\Model\Brand');
        }
        return $this->brandTable;
    }
    
    protected $categoryTable;
    
    public function getCategoryTable()
    {
	if(!$this->categoryTable)
	{
	    $sm = $this->getServiceLocator();
	    $this->categoryTable = $sm->get('Product\Model\Category');
	}
	return $this->categoryTable;
    }
}
